# encoding: utf-8

module OmniauthCallback

  module ClassMethods

    def new_from_provider_data(mobile, password, provider, uid, data)
      User.new do |user|
        user.mobile = mobile
        user.password = password
        user.email = data['email'] if data['email'].present? && !User.where(email: data['email']).exists?
        user.nickname = data['nickname'] if data['nickname'].present? && !User.where(nickname: data['nickname']).exists?
        user.nickname = data['name'] if data['name'].present? && !User.where(nickname: data['name']).exists?
        if user.new_record? && (image=(data['image'] || data['headimgurl'])) && image =~ /^http/
          begin
            filename = File.basename(image)
            upload = ActionDispatch::Http::UploadedFile.new({
              :filename => filename,
              :content_type => (MIME::Types.type_for(filename).first.content_type rescue nil),
              :tempfile => open(image)
            })
            avatar = user.build_avatar(
              image: upload
            )
            avatar.save!
          rescue
          end
        end
        user.is_third_party_account = true
      end
    end 

    def user_third_party_create_enhance
      %w(weibo wechat).each do |provider|
        define_method "find_or_create_for_#{provider}" do |mobile, password, response|
          uid = response['uid'].to_s
          uuid = if provider == 'wechat' && response['extra'] && response['extra']['raw_info'] && response['extra']['raw_info']['unionid']
                   response['extra']['raw_info']['unionid']
                 else
                   uid
                 end
          data = response['info']

          
          if (authorization = UserLoginAuthorization.joins('left join users on users.id = user_login_authorizations.user_id').where('users.mobile': mobile, 'provider' => provider, 'uuid' => uuid).first)
            authorization.bind! if authorization.deleted?
            authorization.user
          else
            user = self.new_record? ? User.new_from_provider_data(mobile, password, provider, uid, data) : self

            if (!user.new_record?) || user.save
              begin
                user.init_nickname_without_save
                user.generate_invite_token_without_save
                user.skip_name_validation = true
                user.save!
              rescue
                #ignore
              end
              user_create_params = {user_id: user.id, provider: provider, uid: uid, uuid: uuid, nickname: data['name'] || data['nickname']}

              if UserLoginAuthorization.create(user_create_params)
                return user
              else
                Rails.logger.warn("User.create_from_third_party_account 失败，#{user.errors.inspect}")
                return nil
              end
            else
              Rails.logger.warn("User.create_from_third_party_account 失败，#{user.errors.inspect}")
              return nil
            end
          end
        end
      end

    end

  end

  def self.included(receiver)
    receiver.extend(ClassMethods)
  end

end
